#include <string.h>

#include "label.h"

widget_t *create_label(parent,text,x,y,width,height,horz,vert)
    widget_t *parent;
    char *text;
    int32_t x,y;
    uint32_t width,height;
    align_t horz;
    align_t vert;
{
    // create the label widget
    widget_t *self = create_widget(parent,x,y,width,height,FALSE);

    // create external information for the widget
    label_t *ext = malloc(sizeof(label_t));
    ext->horz = horz;
    ext->vert = vert;
    ext->font = CreateFont(16,0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,ANSI_CHARSET,
                 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
                 FF_DONTCARE, "Arial");
    self->ext = ext;

    // set the label text
    label_set_text(self, text);

    // set the callback functions
    callback_t *callback = self->callback;
    callback->paint = label_paint;
    callback->free = label_free;

    // return a pointer to the label widget
    return self;
}

void label_set_text(self,text)
    widget_t *self;
    char *text;
{
    // free the old string, if applicable
    if(self->text != NULL) {
        free(self->text);
        self->text = NULL;
    }

    // create memory for the new string and copy the string to it
    self->text = malloc(strlen(text) + 1);
    strcpy(self->text, text);

    // redraw the label
    InvalidateRect(self->hwnd, NULL, FALSE);
}

void label_paint(self,hdc)
    widget_t *self;
    HDC hdc;
{
    // select the label font
    label_t *ext = self->ext;
    HFONT oldfont = SelectObject(hdc, ext->font);

    // format the text horizontal alignment
    UINT format = DT_SINGLELINE;
    if(ext->horz == LEFT)
        format |= DT_LEFT;
    else if(ext->horz == RIGHT)
        format |= DT_RIGHT;
    else
        format |= DT_CENTER;

    // format the text vertical alignment
    if(ext->vert == TOP)
        format |= DT_TOP;
    else if(ext->vert == BOTTOM)
        format |= DT_BOTTOM;
    else
        format |= DT_VCENTER;

    // draw the label text
    RECT rect;
    GetClientRect(self->hwnd, &rect);
    SetTextColor(hdc, RGB(0,0,0));
    SetBkMode(hdc, TRANSPARENT);
    DrawText(hdc, self->text, -1, &rect, format);

    // select the default font
    SelectObject(hdc, oldfont);
}

void label_free(self)
    widget_t *self;
{
    // free text from the widget
    if(self->text != NULL) {
        free(self->text);
    }

    // delete the label
    label_t *ext = self->ext;
    DeleteObject(ext->font);

    // free the widget
    free(self->ext);
    free(self);
}

